﻿namespace YunQue.Core.WebExtension.Middlewares
{
    /// <summary>
    /// 请求中间件
    /// </summary>
    public class LoginPermissionMiddleware
    {
        private readonly RequestDelegate _next;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next"></param>
        public LoginPermissionMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        /// <summary>
        /// invoke
        /// </summary>
        /// <param name="context"></param>
        /// <param name="userContext"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task InvokeAsync(HttpContext context, UserContext userContext)
        {
            //检测是否需要验证身份信息
            bool isAllowAnonymous = context.GetEndpoint()?.Metadata?.GetMetadata<AllowAnonymousAttribute>() != null;
            //不能匿名登录的 userContext 一定有值
            if (!isAllowAnonymous)
            {
                if (string.IsNullOrEmpty(userContext.Id)) throw new Exception("用户未登录");
                if (string.IsNullOrEmpty(userContext.Token)) throw new Exception("token不存在");
                var tenant = await RedisWrapper.GetAsync<TenantModel>(userContext.Token).ConfigureAwait(false);
                if (tenant == null) throw new Exception("租户信息不存在");
                var isLogin = await RedisWrapper.GetAsync<bool?>(userContext.SessionId).ConfigureAwait(false);
                if (isLogin == null || isLogin == false) throw new Exception("登录状态已失效，请重新登录");
            }
            await _next(context);
        }
    }
}
